package com.mini.gateway.filter;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.mini.common.core.constant.HeaderConstants;
import com.mini.common.core.result.ResultCode;
import com.mini.gateway.constant.GatewayConstants;
import com.mini.gateway.util.JwtUtils;
import com.mini.gateway.util.ResponseUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 处理token的全局过滤器
 *
 * @author Zhou Feng
 **/
@Component
public class HeaderFilter implements GlobalFilter, Ordered {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 非JWT或者JWT为空不作处理
        String token = request.getHeaders().getFirst(GatewayConstants.AUTHORIZATION_KEY);
        if (!JwtUtils.hasToken(token, GatewayConstants.AUTHORIZATION_PREFIX)) {
            return chain.filter(exchange);
        }

        //解析token并且获取有效信息，封装为JSON对象
        JSONObject payload = JwtUtils.getPayload(token.replace(GatewayConstants.AUTHORIZATION_PREFIX, StrUtil.EMPTY));
        if (payload.isEmpty()) {
            return ResponseUtils.writeErrorInfo(response, ResultCode.TOKEN_INVALID_OR_EXPIRED);
        }

        // 黑名单
        String jti = payload.getStr(GatewayConstants.JWT_JTI);
        String exp = payload.getStr(GatewayConstants.JWT_EXP);
        Boolean isBlack = redisTemplate.hasKey(GatewayConstants.TOKEN_BLACKLIST_PREFIX + jti);
        if (isBlack != null && isBlack) {
            return ResponseUtils.writeErrorInfo(response, ResultCode.TOKEN_ACCESS_FORBIDDEN);
        }

        // 存在token且不是黑名单，用户信息写入header
        String username = payload.getStr(GatewayConstants.USER_NAME_KEY);
        String nickname = payload.getStr(GatewayConstants.NICK_NAME_KEY);
        String uid = payload.getStr(GatewayConstants.UID_KEY);
        request = exchange.getRequest().mutate()
                .header(HeaderConstants.HEADER_USERNAME, username)
                .header(HeaderConstants.HEADER_NICKNAME, nickname)
                .header(HeaderConstants.HEADER_UID, uid)
                .header(HeaderConstants.HEADER_JTI, jti)
                .header(HeaderConstants.HEADER_EXP, exp)
                .build();
        //重新封装请求
        ServerWebExchange newExchange = exchange.mutate().request(request).build();
        return chain.filter(newExchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
